package org.example.serviceoffice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.model.manage.bean.po.Pay;
import org.example.model.manage.bean.po.StudentPay;
import org.example.model.manage.bean.vo.CreatePayRequest;
import org.example.model.manage.bean.vo.BindPayRequest;
import org.example.serviceoffice.mapper.PayMapper;
import org.example.serviceoffice.mapper.StudentPayMapper;
import org.example.serviceoffice.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 缴费项目服务实现类
 * </p>
 *
 * @author author
 * @since 2025-09-09
 */
@Service
public class PayServiceImpl extends ServiceImpl<PayMapper, Pay> implements PayService {

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private StudentPayMapper studentPayMapper;

    @Override
    @Transactional
    public Pay createPayItem(CreatePayRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("缴费项目信息不能为空");
        }

        if (request.getAmount() == null || request.getAmount() <= 0) {
            throw new IllegalArgumentException("缴费金额必须大于0");
        }

        if (request.getSubject() == null || request.getSubject().trim().isEmpty()) {
            throw new IllegalArgumentException("缴费项目名称不能为空");
        }

        // 创建缴费项目
        Pay pay = new Pay();
        pay.setAmount(request.getAmount());
        pay.setSubject(request.getSubject().trim());

        payMapper.insertPay(pay);
        return pay;
    }

    @Override
    @Transactional
    public int bindPayToStudents(BindPayRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("绑定请求不能为空");
        }

        if (request.getPayId() == null) {
            throw new IllegalArgumentException("缴费项目ID不能为空");
        }

        if (request.getStudentIds() == null || request.getStudentIds().isEmpty()) {
            throw new IllegalArgumentException("学生ID列表不能为空");
        }

        // 验证缴费项目是否存在
        Pay pay = payMapper.selectById(request.getPayId());
        if (pay == null) {
            throw new IllegalArgumentException("缴费项目不存在");
        }

        // 批量创建学生缴费关联
        List<StudentPay> studentPayList = new ArrayList<>();
        for (String studentId : request.getStudentIds()) {
            StudentPay studentPay = new StudentPay();
            studentPay.setStudentId(studentId);
            studentPay.setPayId(request.getPayId());
            studentPay.setCheckStatus(0); // 0表示未缴费
            studentPayList.add(studentPay);
        }

        return studentPayMapper.insertBatch(studentPayList);
    }

}